<template>
  <div class="class-form-container">
    <el-card class="class-form-card">
      <template #header>
        <div class="card-header">
          <h2>{{ isEdit ? '编辑班级' : '添加班级' }}</h2>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="class-form"
      >
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入班级名称" />
        </el-form-item>

        <el-form-item label="所属课程" prop="courseId">
          <el-select
            v-model="form.courseId"
            placeholder="请选择所属课程"
            style="width: 100%"
          >
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="班级描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入班级描述"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '保存修改' : '添加班级' }}
          </el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import logger from '@/utils/Logger'

export default {
  name: 'ClassForm',
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const formRef = ref(null)

    // 状态
    const submitting = ref(false)
    const form = reactive({
      id: '',
      name: '',
      courseId: '',
      courseName: '',
      description: '',
      studentCount: 0
    })

    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入班级名称', trigger: 'blur' },
        { min: 2, max: 50, message: '班级名称长度应为2-50个字符', trigger: 'blur' }
      ],
      courseId: [
        { required: true, message: '请选择所属课程', trigger: 'change' }
      ]
    }

    // 计算属性
    const isEdit = computed(() => {
      return route.params.id !== undefined
    })

    const courses = computed(() => {
      return store.getters.getCourses
    })

    // 方法
    const loadCourses = async () => {
      try {
        // 从后端API获取课程数据
        await store.dispatch('fetchCourses')
        logger.info('课程列表加载成功', { count: courses.value.length })
      } catch (error) {
        logger.error('加载课程列表失败', error)
        ElMessage.error('加载课程列表失败')
      }
    }

    const loadClassData = () => {
      if (isEdit.value) {
        const classId = route.params.id
        const classData = store.getters.getClasses.find(c => c.id === classId)

        if (classData) {
          Object.assign(form, classData)
          logger.info('班级数据加载成功', { classId })
        } else {
          ElMessage.error('未找到班级数据')
          router.push('/class/list')
        }
      }
    }

    const submitForm = async () => {
      if (!formRef.value) return

      await formRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true

          try {
            // 获取课程名称
            const selectedCourse = courses.value.find(c => c.id === form.courseId)
            form.courseName = selectedCourse ? selectedCourse.name : ''

            // 确保 courseId 是数字类型
            if (form.courseId && typeof form.courseId === 'string') {
              form.courseId = parseInt(form.courseId, 10)
            }

            console.log('Form data before submission:', form)

            if (isEdit.value) {
              // 更新班级
              await store.dispatch('updateClass', { id: form.id, classData: form })
              ElMessage.success('班级更新成功')
              logger.info('班级更新成功', { classId: form.id, className: form.name })
            } else {
              // 添加班级
              const newClass = {
                name: form.name,
                courseId: form.courseId,
                studentCount: 0
              }
              await store.dispatch('createClass', newClass)
              ElMessage.success('班级添加成功')
              logger.info('班级添加成功', { className: newClass.name })
            }

            router.push('/class/list')
          } catch (error) {
            logger.error(isEdit.value ? '更新班级失败' : '添加班级失败', error)
            ElMessage.error(isEdit.value ? '更新班级失败' : '添加班级失败')
          } finally {
            submitting.value = false
          }
        }
      })
    }

    const goBack = () => {
      router.push('/class/list')
    }

    // 生命周期钩子
    onMounted(() => {
      loadCourses()
      loadClassData()
    })

    return {
      formRef,
      form,
      rules,
      isEdit,
      courses,
      submitting,
      submitForm,
      goBack
    }
  }
}
</script>

<style scoped>
.class-form-container {
  max-width: 800px;
  margin: 0 auto;
}

.class-form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.class-form {
  margin-top: 20px;
}
</style>
